<template>
  <div class="container-pt">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      fixed
      title="我的文章"
    />
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <article-list
        :disable-swiper="false"
        v-for="item in articleList"
        :key="item.id"
        :item="item"
      >
        <van-button square type="warning" @click="update(item)" text="修改" />
        <van-button square type="danger" text="删除" @click="del(item.id)" />
      </article-list>
    </van-list>

    <van-popup v-model="active" style="height: 100%" position="bottom">
      <van-nav-bar title="修改文章">
        <template #right>
          <van-icon name="close" @click="active = false" size="18" />
        </template>
      </van-nav-bar>
      <article-form
        ref="article"
        :item="articleItem"
        @closePopup="close"
        :flag="active"
      ></article-form>
    </van-popup>
  </div>
</template>

<script>
import articleList from '@/components/article-list.vue'
import articleForm from '@/components/article-form.vue'
import { delArticle, getMyArticle } from '@/api/artice'
export default {
  components: { articleList, articleForm },
  data() {
    return {
      active: false,
      page: 1,
      limit: 10,
      loading: false,
      finished: false,
      articleList: [],
      articleItem: {}
    };
  },
  methods: {
    async onLoad() {
      const res = await getMyArticle({
        page: this.page,
        limit: this.limit
      })
      this.loading = false
      this.page++
      // if (this.articleList.length > 0 && res.data.currentPage === 1) {
      //   return
      // }
      this.articleList.push(...res.data.data)
      if (this.page > res.data.totalPages) {
        this.finished = true
      }
    },
    async del(id) {
      try {
        const res = await delArticle(id)
        if (res.errno !== 0) {
          return this.$toast.fail(res.errmsg)
        }
        this.$toast.success('删除成功！')
        this.page = 1
        this.articleList = []
        this.onLoad()
      } catch (error) {
        return
      }
    },
    update(item) {
      this.active = true
      this.articleItem = item
      this.$nextTick(() => {
        this.$refs.article.editEcho()
      })
    },
    close() {
      // 编辑完毕后关闭popup
      this.active = false
      this.page = 1
      this.articleList = []
      this.onLoad()
    }
  },

}
</script>

<style scoped>
.van-button {
  height: 100%;
}
</style>